<template>
  <div class="goods-image">
    <!-- 放大后的图片 -->
    <div
      v-show="!isOutside"
      class="large"
      :style="[
        {
          backgroundImage: `url(${pictures[currentIndex]})`,
          backgroundPosition: `${bg.x}px ${bg.y}px`,
        },
      ]"
    ></div>
    <!-- 商品图片 -->
    <div class="middle" ref="target">
      <img :src="pictures[currentIndex]" alt="" />
      <!-- 蒙层 -->
      <div
        v-show="!isOutside"
        class="layer"
        :style="{ left: `${position.left}px`, top: `${position.top}px` }"
      ></div>
    </div>
    <!-- 商品小图 -->
    <ul class="small">
      <li v-for="(img, i) in pictures" :key="i" @mouseenter="currentIndex = i">
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { reactive, ref, watch } from 'vue-demi'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    pictures: {
      type: Array,
      default: () => []
    }
  },
  // width/2 + left = elementX
  setup () {
    const currentIndex = ref(0)
    const target = ref(null)
    const position = reactive({ left: 0, top: 0 })
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // 大图放大比例数据
    const bg = reactive({ x: 0, y: 0 })
    watch([elementX, elementY], () => {
      if (elementX.value < 100) {
        position.left = 0
      } else if (elementX.value > 300) {
        position.left = 200
      } else {
        position.left = +elementX.value - 100
      }
      if (elementY.value < 100) {
        position.top = 0
      } else if (elementY.value > 300) {
        position.top = 200
      } else {
        position.top = +elementY.value - 100
      }
      bg.x = -position.left * 2
      bg.y = -position.top * 2
    })

    return { position, currentIndex, target, elementX, elementY, isOutside, bg }
  }
}
</script>
<style scoped lang="less">
.large {
  position: absolute;
  top: 0;
  left: 412px;
  width: 400px;
  height: 400px;
  z-index: 500;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-repeat: no-repeat;
  background-size: 800px 800px;
  background-color: #f8f8f8;
}
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
